package services;

import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import play.libs.Codec;

import com.aton.db.SessionFactory;

import models.DrCaseContent;
import models.DrMicrophoneExample;
import models.DrVKeywordsExample;
import models.DrWords;
import models.DrWordsExample;
import models.SystemLog;
import models.SystemOperator;
import models.mapper.DrKeywordsMapper;
import models.mapper.DrVKeywordsMapper;
import models.mapper.DrWordsMapper;
import models.mapper.SystemLogMapper;

public class CaseWordService {

	public static boolean addCaseWord(DrWords drWord, SystemOperator loginUser,
			String ip) {
		
		SqlSession ss = SessionFactory.INSTANCE.getSqlSessionWithoutAutoCommit();
		try{
			DrWordsMapper mapper=ss.getMapper(DrWordsMapper.class);
			mapper.insert(drWord);
			//插入日志
			SystemLog log=new SystemLog(Codec.UUID(),loginUser.getOperatorid(),ip,"新增庭审词条","新增庭审词条",new Date());
			SystemLogMapper logMapper=ss.getMapper(SystemLogMapper.class);
			logMapper.insert(log);
			ss.commit();
		}catch(Exception e){
			e.printStackTrace();
			ss.rollback();
			return false;
		}finally{
			ss.close();
		}
		return Boolean.TRUE;
	}

	public static List<DrWords> findCaseWordByCaseId(String caseid) {
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrWordsMapper mapper=ss.getMapper(DrWordsMapper.class);
			DrWordsExample example=new DrWordsExample();
			example.setOrderByClause("createDate desc");
			DrWordsExample.Criteria c=example.createCriteria();
			c.andCaseidEqualTo(caseid);
			return mapper.selectByExample(example);
		}finally{
			ss.close();
		}
	}

	public static boolean deleteCaseWordById(String caseWordid,
			SystemOperator loginUser, String ip) {
		
				SqlSession ss = SessionFactory.INSTANCE.getSqlSessionWithoutAutoCommit();
				try{
					DrWordsMapper mapper=ss.getMapper(DrWordsMapper.class);
					mapper.deleteByPrimaryKey(caseWordid);
					ss.commit();
				}catch(Exception e){
					e.printStackTrace();
					ss.rollback();
					return false;
				}finally{
					ss.close();
				}
				return true;
	}
	/**
	 * 根据内容查询词条
	 * @param context
	 * @return
	 */
	public static DrWords getByName(String context) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrWordsMapper mapper=ss.getMapper(DrWordsMapper.class);
			DrWordsExample example=new DrWordsExample();
			DrWordsExample.Criteria c=example.createCriteria();
			c.andContextEqualTo(context);
			if(mapper.selectByExample(example)!=null&&mapper.selectByExample(example).size()>0){
				return mapper.selectByExample(example).get(0);
			}
			return null;
		}finally{
			ss.close();
		}
	}

}
